package net.xuele.learn.mq;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MessageProducer {


    /**
     * The Default mq producer.
     */
    @Autowired
    private DefaultMQProducer defaultMQProducer;

    @Autowired
    private RocketMqProperty rocketMqProperty;

    /**
     * Send message.
     *
     * @param msg the msg
     * @return the send result
     */
    public SendResult sendMessage(Message msg) {
        SendResult sendResult = null;
        try {
            sendResult = defaultMQProducer.send(msg);

        } catch (MQClientException | InterruptedException | MQBrokerException | RemotingException e) {
            log.error("MessageProduce sendMessage key: {}, exception is : {}", msg.getKeys(), e);
        }
        log.info("MessageProduce sendMessage sendResult: {}", sendResult);
        return sendResult;
    }

    /**
     * Send claim message.
     *
     * @param keys the keys
     * @param body the body
     * @return the send result
     */
    public SendResult sendMessage(String keys, byte[] body,String msgTag) {
        Message msg = new Message("testTopic", msgTag, keys, body);
        SendResult sendResult = sendMessage(msg);
        return sendResult;
    }
}
